﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.huigo.Framework.Model;
using com.loto.Common.DBUtility;
using System.Data.SqlClient;

namespace com.huigo.Framework.BLL
{
    public class InvoiceOrder
    {
        public static Model.InvoiceOrder GetUnpayOrderInfoById(long custId, long orderId)
        {
            Model.InvoiceOrder orderInfo = new Model.InvoiceOrder();
            orderInfo.OrderId = orderId;
            orderInfo.OrderCustFid = custId;
            orderInfo.OrderStatusFid = (int)Dict.InvoiceStatus.UnPay;
            List<string> fields = new List<string>() 
            {   
                "ORDER_ID",
                "ORDER_NO",
                "ORDER_PAY_AMOUNT",
            };
            return SqlServerDal.InvoiceOrder.GetItem(orderInfo, fields, null, null);
        }
        /// <summary>
        /// 根据订单ID查询订单信息
        /// </summary>
        /// <param name="custFid">用户ID</param>
        /// <param name="orderId">订单ID</param>
        /// <returns></returns>
        public static Model.InvoiceOrder GetInvoiceOrderInfoById(long custFid, long orderId)
        {
            Model.InvoiceOrder orderInfo = new Model.InvoiceOrder();
            orderInfo.OrderId = orderId;
            orderInfo.OrderCustFid = custFid;
            List<string> fields = new List<string>() 
            {   
                "ORDER_ID",
                "ORDER_NO",
                "ORDER_PAY_AMOUNT",
                "ORDER_PROVINCE",
                "ORDER_CITY",
                "ORDER_ADDRESS",
                "ORDER_CONTACT",
                "ORDER_TEL",
                "ORDER_FEDEX_NO",
                "ORDER_FEDEX"
            };
            return SqlServerDal.InvoiceOrder.GetItem(orderInfo, fields, null, null);
        }
        /// <summary>
        /// 提交申领订单
        /// </summary>
        /// <param name="productId">产品ID</param>
        /// <param name="count">申领张数</param>
        /// <param name="shipping">配送方式</param>
        /// <param name="province">省份</param>
        /// <param name="city">城市</param>
        /// <param name="address">地址</param>
        /// <param name="contacts">联系人</param>
        /// <param name="contactsTel">联系电话</param>
        /// <param name="money">总金额</param>
        /// <param name="custFid">用户ID</param>
        /// <returns></returns>
        public static long AddInvoiceOrder(long productId, int count, byte shipping, string province, string city, string address, string contacts, string contactsTel, decimal money, long custFid)
        {
            bool result = false;
            long orderId = 0;
            string productName = string.Empty;
            if (productId > 0)
            {
                Model.ProductInfo product = new com.huigo.Framework.Model.ProductInfo();
                product.ProductId = productId;
                List<string> fileds = new List<string>()
                {
                    "PRODUCT_NAME"
                };
                Model.ProductInfo productInfo = SqlServerDal.ProductInfo.GetItem(product, fileds, null, null);
                if (productInfo != null)
                {
                    productName = productInfo.ProductName;
                }
            }
            using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
            {
                if ((money > 0 && (shipping == (byte)Dict.InvoiceDeliverType.Send)) || (shipping == (byte)Dict.InvoiceDeliverType.BySelf || shipping == (byte)Dict.InvoiceDeliverType.ToPay))
                {
                    Model.InvoiceOrder invoiceOrder = new com.huigo.Framework.Model.InvoiceOrder();
                    invoiceOrder.OrderCustFid = custFid;
                    invoiceOrder.OrderNo = "V" + Others.GetIndex();
                    invoiceOrder.OrderProductFid = productId;
                    invoiceOrder.OrderProductName = productName;
                    invoiceOrder.OrderPayAmount = money;
                    invoiceOrder.OrderAmount = money;
                    invoiceOrder.OrderCreatedOn = DateTime.Now;
                    invoiceOrder.OrderLastUpdatedOn = DateTime.Now;
                    invoiceOrder.OrderSource = 1;
                    if (shipping == 1)
                    {
                        invoiceOrder.OrderStatusFid = 1;
                    }
                    else
                    {
                        invoiceOrder.OrderStatusFid = 2;
                    }
                    invoiceOrder.OrderPaperCount = count;
                    invoiceOrder.OrderDeliverType = shipping;
                    invoiceOrder.OrderProvince = province;
                    invoiceOrder.OrderCity = city;
                    invoiceOrder.OrderAddress = address;
                    invoiceOrder.OrderContact = contacts;
                    invoiceOrder.OrderTel = contactsTel;
                    orderId = SqlserverDal.InvoiceOrder.AddInvoiceOrder(invoiceOrder, trans);
                    if (orderId > 0)
                    {
                        Model.InvoiceOrderFlow invoiceOrderFlow = new com.huigo.Framework.Model.InvoiceOrderFlow();
                        invoiceOrderFlow.FlowOrderFid = orderId;
                        invoiceOrderFlow.FlowOperFid = custFid;
                        if (shipping == 1)
                        {
                            invoiceOrderFlow.FlowOrderStatusFid = 1;
                        }
                        else
                        {
                            invoiceOrderFlow.FlowOrderStatusFid = 2;
                        }
                        invoiceOrderFlow.FlowCreatedOn = DateTime.Now;
                        invoiceOrderFlow.FlowMemo = "提交申领订单";
                        result = SqlServerDal.InvoiceOrderFlow.Insert(invoiceOrderFlow, null);
                        if (result)
                        {
                            trans.Commit();
                        }
                        else
                        {
                            trans.Rollback();
                        }
                    }
                }
            }
            return orderId;
        }
        /// <summary>
        /// 查询发票
        /// </summary>
        /// <param name="custFid">用户ID</param>
        /// <param name="orderNo">订单编号</param>
        /// <param name="start">订单开始时间</param>
        /// <param name="end">订单结束时间</param>
        /// <param name="type">订单状态</param>
        /// <param name="productId">产品ID</param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static List<Model.InvoiceOrder> GetInvoiceOrderList(long custFid, string orderNo, DateTime start, DateTime end, int type, long productId, int pageSize, int pageIndex)
        {
            List<string> fileds = new List<string>()
            {
                "ORDER_ID,ORDER_NO,ORDER_PRODUCT_NAME,ORDER_AMOUNT,ORDER_PAY_AMOUNT,ORDER_CREATED_ON,ORDER_PAID_ON,ORDER_LAST_UPDATED_ON,ORDER_STATUS_FID,ORDER_PAPER_COUNT,ORDER_DELIVER_TYPE,ORDER_REAL_PAPER_COUNT,STATUS_VIEW"
            };
            List<JoinStatement> joinList = new List<JoinStatement>()
            {
                new JoinStatement ("left","HG_INVOICE_ORDER_STATUS","ORDER_STATUS_FID=STATUS_ID")
            };
            List<WhereStatement> whereList = new List<WhereStatement>();
            if (!string.IsNullOrEmpty(orderNo))
            {
                whereList.Add(new WhereStatement("ORDER_NO", "=", "'" + orderNo + "'", "and"));
            }
            if (start != DateTime.MinValue && end != DateTime.MinValue)
            {
                whereList.Add(new WhereStatement("ORDER_CREATED_ON", "between", "'" + start + "' AND '" + end + "'", "AND"));
            }
            if (type > -1)
            {
                whereList.Add(new WhereStatement("ORDER_STATUS_FID", "=", "" + type + "", "and"));
            }
            if (productId > 0)
            {
                whereList.Add(new WhereStatement("ORDER_PRODUCT_FID", "=", "" + productId + "", "and"));
            }
            whereList.Add(new WhereStatement("ORDER_CUST_FID", "=", "" + custFid + "", ""));

            List<OrderByStatement> orderList = new List<OrderByStatement>()
            {
                new OrderByStatement("ORDER_CREATED_ON",false)
            };

            List<Model.InvoiceOrder> order = null;
            int recordCount = 0;
            int pageCount = 0;
            order = SqlServerDal.InvoiceOrder.GetItemsByProc(fileds, joinList, whereList, orderList, "[PROC_PAGINATION_OUT]", pageSize, pageIndex, out recordCount, out pageCount, null);
            order.ForEach(delegate(Model.InvoiceOrder info)
            {
                info.RecordCount = recordCount;
                info.PageCount = pageCount;
            });
            return order;
        }
        public static List<Model.InvoiceOrder> GetInvoiceOrderInfo(string InvoiceOrderNO, DateTime InvoiceOrderStart, DateTime InvoiceOrderEnd, string custName, int InvoiceOrderStatus, string proName, int pageSize, int pageIndex)
        {
            List<string> fields = new List<string>() 
             {
                @"[ORDER_ID]
                  ,[ORDER_CUST_FID]
                  ,[ORDER_NO]
                  ,[ORDER_PRODUCT_FID]
                  ,[ORDER_PRODUCT_NAME]
                  ,[ORDER_AMOUNT]
                  ,[ORDER_PAY_AMOUNT]
                  ,[ORDER_DISCOUNT_AMOUNT]
                  ,[ORDER_SCORE_AMOUNT]
                  ,[ORDER_CREATED_ON]
                  ,[ORDER_PAID_ON]
                  ,[ORDER_LAST_UPDATED_ON]
                  ,[ORDER_SOURCE]
                  ,[ORDER_FROM]
                  ,[ORDER_STATUS_FID]
                  ,[ORDER_PAPER_COUNT]
                  ,[ORDER_DELIVER_TYPE]
                  ,[ORDER_PROVINCE]
                  ,[ORDER_CITY]
                  ,[ORDER_ADDRESS]
                  ,[ORDER_CONTACT]
                  ,[ORDER_TEL]
                  ,[ORDER_REAL_PAPER_COUNT]
                  ,[ORDER_FEDEX_NO]
                  ,[ORDER_FEDEX],CUST_NAME,STATUS_DESC,PRODUCT_TYPE_FID"
             };
            List<JoinStatement> joinList = new List<JoinStatement>();
            joinList.Add(new JoinStatement("LEFT", "[HG_PRODUCT_INFO]", "ORDER_PRODUCT_FID=PRODUCT_ID"));
            joinList.Add(new JoinStatement("LEFT", "[HG_CUST_INFO]", "ORDER_CUST_FID=CUST_ID"));
            joinList.Add(new JoinStatement("LEFT", "[HG_INVOICE_ORDER_STATUS]", "ORDER_STATUS_FID=STATUS_ID"));
            List<OrderByStatement> OrderByStatement = new List<OrderByStatement>() 
             {
                 new OrderByStatement("ORDER_CREATED_ON",false)
             };
            List<WhereStatement> whereList = new List<WhereStatement>();
            if (!string.IsNullOrEmpty(InvoiceOrderNO))
            {
                whereList.Add(new WhereStatement("ORDER_NO", "=", "'" + InvoiceOrderNO + "'", "AND"));
            }
            if (InvoiceOrderStart != DateTime.MinValue && InvoiceOrderEnd != DateTime.MinValue)
            {
                whereList.Add(new WhereStatement("ORDER_CREATED_ON", "BETWEEN", "'" + InvoiceOrderStart + "' AND '" + InvoiceOrderEnd + "'", "AND"));
            }
            if (InvoiceOrderStatus > -1)
            {
                whereList.Add(new WhereStatement("ORDER_STATUS_FID", "=", InvoiceOrderStatus.ToString(), "AND"));
            }
            if (!string.IsNullOrEmpty(custName))
            {
                whereList.Add(new WhereStatement("CUST_NAME", "like", "'%" + custName + "%'", "AND"));
            }
            if (!string.IsNullOrEmpty(proName))
            {
                whereList.Add(new WhereStatement("ORDER_PRODUCT_FID", "=", proName, "AND"));

            }
            if (whereList.Count == 0)
            {
                whereList.Add(new WhereStatement("ORDER_STATUS_FID", "=", ((int)Dict.InvoiceStatus.UnCheck).ToString(), "AND"));
            }
            whereList.Add(new WhereStatement("PRODUCT_STATUS", "=", ((int)Dict.IsActive.Yes).ToString(), ""));
            List<Model.InvoiceOrder> InvoiceOrderList = null;
            int recordCount = 0;
            int pageCount = 0;
            InvoiceOrderList = SqlServerDal.InvoiceOrder.GetItemsByProc(fields, joinList, whereList, OrderByStatement, "[PROC_PAGINATION_OUT]", pageSize, pageIndex, out recordCount, out pageCount, null);
            InvoiceOrderList.ForEach(delegate(Model.InvoiceOrder info)
            {
                info.RecordCount = recordCount;
                info.PageCount = pageCount;
            });
            return InvoiceOrderList;

        }

        public static Model.InvoiceOrder GetInvoiceOrderByID(long invoiceOrderID)
        {
            List<string> fields = new List<string>() 
             {
                @"[ORDER_ID]
                  ,[ORDER_CUST_FID]
                  ,[ORDER_NO]
                  ,[ORDER_PRODUCT_FID]
                  ,[ORDER_PRODUCT_NAME]
                  ,[ORDER_AMOUNT]
                  ,[ORDER_PAY_AMOUNT]
                  ,[ORDER_DISCOUNT_AMOUNT]
                  ,[ORDER_SCORE_AMOUNT]
                  ,[ORDER_CREATED_ON]
                  ,[ORDER_PAID_ON]
                  ,[ORDER_LAST_UPDATED_ON]
                  ,[ORDER_SOURCE]
                  ,[ORDER_FROM]
                  ,[ORDER_STATUS_FID]
                  ,[ORDER_PAPER_COUNT]
                  ,[ORDER_DELIVER_TYPE]
                  ,[ORDER_PROVINCE]
                  ,[ORDER_CITY]
                  ,[ORDER_ADDRESS]
                  ,[ORDER_CONTACT]
                  ,[ORDER_TEL]
                  ,[ORDER_REAL_PAPER_COUNT]
                  ,[ORDER_FEDEX_NO]
                  ,[ORDER_FEDEX]"
             };
            Model.InvoiceOrder InvoiceOrder = new com.huigo.Framework.Model.InvoiceOrder();
            InvoiceOrder.OrderId = invoiceOrderID;
            return SqlServerDal.InvoiceOrder.GetItem(InvoiceOrder, fields, null, null);
        }
        /// <summary>
        /// 审核发票订单
        /// </summary>
        /// <param name="invoiceOrderID">订单id</param>
        /// <param name="status">当前状态</param>
        /// <param name="userID">操作人</param>
        /// <param name="Meno">审核不通过添加备注</param>
        /// <param name="Fedex">快递单号</param>
        /// <param name="FedexComPany">快递公司</param>
        /// <returns></returns>
        public static bool updateInvoiceOrder(long invoiceOrderID, int status, long userID,string Meno,string Fedex,string FedexComPany)
        {
            Model.InvoiceOrder order = GetInvoiceOrderByID(invoiceOrderID);
            Model.InvoiceOrder updateOrder = new com.huigo.Framework.Model.InvoiceOrder();
            int invoiceStatus = 0;
            string statusMeno = string.Empty;
            if (order != null)
            {
                switch (status)
                {
                    case (int)Dict.UpdateInvoiceOrderStatus.CheckFail:
                        invoiceStatus = (int)Dict.InvoiceStatus.CheckFail;
                        statusMeno = Meno;//审核不通过
                        updateOrder.OrderStatusFid = invoiceStatus;
                        break;
                    case (int)Dict.UpdateInvoiceOrderStatus.CheckOK:
                        invoiceStatus = (int)Dict.InvoiceStatus.CheckSuc;
                        statusMeno = com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictInvoiceStatus, (invoiceStatus));//审核通过
                        updateOrder.OrderStatusFid = invoiceStatus;
                        break;
                    case (int)Dict.UpdateInvoiceOrderStatus.DeliverSuc:
                        invoiceStatus = (int)Dict.InvoiceStatus.DeliverSuc;
                        statusMeno = com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictInvoiceStatus, (invoiceStatus));//配送
                        updateOrder.OrderStatusFid = invoiceStatus;
                        updateOrder.OrderFedex=FedexComPany;
                        updateOrder.OrderFedexNo=Fedex;
                        break;
                    default:
                        break;
                }
                updateOrder.OrderLastUpdatedOn = DateTime.Now;
                List<WhereStatement> whereList = new List<WhereStatement>()
                {
                    new WhereStatement("ORDER_ID","=",invoiceOrderID.ToString(),"")
                };
                using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                {
                    try
                    {
                        SqlServerDal.InvoiceOrder.Update(updateOrder, whereList, trans);
                        BLL.InvoiceOrderFlow.AddInvoiceOrderFlow(invoiceOrderID, userID, invoiceStatus, statusMeno, trans);
                        trans.Commit();
                        return true;
                    }
                    catch
                    {
                        trans.Rollback();
                        return false;
                    }

                }
            }
            else
            {
                return false;
            }

        }

    }
}
